const app = getApp()
Page({
  data: {
    largeImage: '',
    originalLargeImage: '', // 缓存原始图片
    smallImages: Array(10).fill(''),
    originalSmallImages: Array(10).fill(''), // 缓存原始图片
    dishName: '', // 菜品名称
    mainIngredient: '', // 主料
    flavur: '',// 调料
    ingredients: '',// 辅料
    taste: '',// 口味
    practice: '', // 做法
    isSave: true,
  },
  onLoad() {
    this.widget = this.selectComponent('.widget')
  },
  chooseImage(event) {
    const { currentTarget } = event
    const self = this;
    let itemArr = ['从相册选择', '拍照', '编辑']
    if (currentTarget.dataset.area === 'large') {
      if (self.data.largeImage === '') {
        itemArr = ['从相册选择', '拍照']
      }
    } else if (currentTarget.dataset.area === 'small') {
      let pos = currentTarget.dataset.index
      if (self.data.smallImages[pos] === '') {
        itemArr = ['从相册选择', '拍照']
      }
    }
    wx.showActionSheet({
      itemList: itemArr,
      success(res) {
        switch (res.tapIndex) {
          case 0:
            // 从相册选择图片
            self.chooseMedia(currentTarget, "album")
            break
          case 1:
            // 调取相机拍照
            self.chooseMedia(currentTarget, "camera")
            break
          case 2:
            // 编辑已经选择的图片
            self.editImage(currentTarget)
            break
          default:
            console.error("未知选项")
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  inputText(event) {
    let { dataset } = event.currentTarget
    let self = this
    wx.showModal({
      placeholderText: '请输入内容',
      showCancel: true,
      editable: true,
      content: this.data[dataset.model],
      success: function (res) {
        if (res.confirm) {
          self.setData({
            [dataset.model]: res.content
          })
        }
      }
    })
  },
  chooseMedia(currentTarget, sourceType) {
    let count = 1
    if (sourceType === 'album') {
      if (currentTarget.dataset.area === 'small') {
        count = 10
      }
    }
    let self = this
    wx.chooseMedia({
      count: count,
      mediaType: ['image'],
      sizeType: ['original'],
      sourceType: [sourceType],
      success: async function ({ tempFiles }) {
        if (currentTarget.dataset.area === 'large') {
          const imagePath = tempFiles[0].tempFilePath
          app.globalData.clipImgSrc = imagePath
          const dpi = await self.getImageDPI(tempFiles[0].tempFilePath)
          if (dpi && dpi < 300) {
            wx.showModal({
              title: '提示',
              content: `图片分辨率为${dpi}dpi，图片建议分辨率为300dpi，像素不够请求换图，强行放大会虚化，是否继续？`,
              success(res) {
                if (res.confirm) {
                  self.setData({
                    originalLargeImage: imagePath,
                  })
                  self.cropImage({
                    src: imagePath,
                    success: function (tempFilePath) {
                      self.setData({ largeImage: tempFilePath })
                    }
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else {
            self.setData({ originalLargeImage: imagePath })
            self.cropImage({
              src: imagePath,
              success: function (tempFilePath) {
                self.setData({ largeImage: tempFilePath })
              }
            })
          }
        } else if (currentTarget.dataset.area === 'small') {
          let pos = currentTarget.dataset.index
          let images = [...self.data.smallImages]
          let originalImages = [...self.data.originalSmallImages]
          if (tempFiles.length === 1) {
            const imagePath = tempFiles[0].tempFilePath
            const dpi = await self.getImageDPI(imagePath)
            if (dpi && dpi < 300) {
              wx.showModal({
                title: '提示',
                content: `图片分辨率为${dpi}dpi，图片建议分辨率为300dpi，像素不够请求换图，强行放大会虚化，是否继续？`,
                success(res) {
                  if (res.confirm) {
                    originalImages[pos] = imagePath
                    self.setData({
                      originalSmallImages: originalImages
                    })
                    self.cropImage({
                      src: imagePath,
                      cropScale: '1:1',
                      success: function (tempFilePath) {
                        images[pos] = tempFilePath
                        self.setData({
                          smallImages: images
                        })
                      }
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            } else {
              originalImages[pos] = tempFiles[0].tempFilePath
              self.setData({
                originalSmallImages: originalImages
              })
              self.cropImage({
                src: imagePath,
                cropScale: '1:1',
                success: function (tempFilePath) {
                  images[pos] = tempFilePath
                  self.setData({
                    smallImages: images
                  })
                }
              })
            }
          } else {
            tempFiles.forEach((image, index) => {
              let i = (index + pos) % 10
              images[i] = image.tempFilePath
            })
            self.setData({
              smallImages: images,
              originalSmallImages: images
            })
          }
        }
      }
    })
  },
  editImage(currentTarget) {
    let self = this
    if (currentTarget.dataset.area === 'large') {
      if (!self.data.originalLargeImage) {
        return
      }
      self.cropImage({
        src: self.data.originalLargeImage,
        success: function (tempFilePath) {
          self.setData({ largeImage: tempFilePath })
        }
      })
    } else if (currentTarget.dataset.area === 'small') {
      let pos = currentTarget.dataset.index
      let images = [...self.data.smallImages]
      if (!self.data.originalSmallImages[pos]) {
        return
      }
      self.cropImage({
        src: self.data.originalSmallImages[pos],
        cropScale: '1:1',
        success: function (tempFilePath) {
          images[pos] = tempFilePath
          self.setData({
            smallImages: images
          })
        }
      })
    }
  },
  cropImage(option) {
    wx.navigateTo({
      url: '/pages/image-cropper/index',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          option.success(data.tempFilePath)
        },
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { imagePath: option.src, cropScale: option.cropScale })
      },
      fail: console.error
    })
  },
  // 保存到相册
  saveAsImage() {
    const that = this
    this.setData({
      isSave: false
    })
    wx.showLoading({
      title: '图片生成中',
    })
    setTimeout(() => {
      this.createSelectorQuery()
        .select("#view")
        .node()
        .exec(res => {
          const node = res[0].node
          node.takeSnapshot({
            type: 'arraybuffer',
            format: 'png',
            success: (res) => {
              const tempFilePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.png`
              const fs = wx.getFileSystemManager();
              // 将海报数据写入本地文件
              fs.writeFileSync(tempFilePath, res.data, 'binary')
              wx.getSetting({
                success(res) {
                  if (res.authSetting['scope.writePhotosAlbum']) {
                    that.saveToPhotosAlbum(fs, tempFilePath)
                  } else {
                    wx.authorize({
                      scope: 'scope.writePhotosAlbum',
                      success() {
                        that.saveToPhotosAlbum(fs, tempFilePath);
                      },
                      fail(error) {
                        console.log(error)
                        wx.hideLoading()
                        wx.showModal({
                          content: '检测到您没打开相册功能权限，是否去设置打开？',
                          confirmText: "确认",
                          cancelText: "取消",
                          success: function (res) {
                            if (res.confirm) {
                              wx.openSetting({
                                success: (res) => { }
                              })
                            }
                          }
                        })
                      }
                    })
                  }
                },
                fail() {
                  wx.hideLoading()
                }
              })
            },
            fail(error) {
              wx.hideLoading()
              console.log(error)
            },
            complete() {
              that.setData({
                isSave: true
              })
            }
          })
        })
    }, 500)
  },
  saveToPhotosAlbum(fs, tempFilePath) {
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success() {
        // 删除文件
        fs.unlink({
          filePath: tempFilePath,
          success(res) {
            console.log(res)
          },
          fail(res) {
            console.error(res)
          }
        })
        wx.showToast({
          title: '保存成功',
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },
  fillArrayToTen(arr) {
    while (arr.length < 10) {
      arr.push("");
    }
    return arr;
  },
  fillArrayToRow(arr) {
    let fillLenth = 5
    if (arr.length > 5) {
      fillLenth = 10
    }
    while (arr.length < fillLenth) {
      arr.push("");
    }
    return arr;
  },
  // 蓝牙打印
  bluetoothPrint() {
    const that = this
    wx.getSetting({
      success(res) {
        // 已有蓝牙模块
        const authSetting = res.authSetting
        if (authSetting['scope.bluetooth']) {
          that.print()
        } else {
          wx.authorize({
            scope: 'scope.bluetooth',
            success() {
              that.print()
            },
            fail(error) {
              console.log(error)
              wx.hideLoading()
              wx.showModal({
                content: '检测到您没打开蓝牙权限，是否去设置打开？',
                confirmText: "确认",
                cancelText: "取消",
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => { }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  cloudStorage() {
    const dishName = this.data.dishName + new Date().getTime() + '.png'
    const that = this
    this.setData({
      isSave: false
    })
    wx.showLoading({
      title: '图片上传中',
    })
    setTimeout(() => {
      this.createSelectorQuery()
        .select("#view")
        .node()
        .exec(res => {
          const node = res[0].node
          node.takeSnapshot({
            type: 'arraybuffer',
            format: 'png',
            success: (res) => {
              console.log(res)
              const tempFilePath = `${wx.env.USER_DATA_PATH}/${dishName}`
              const fs = wx.getFileSystemManager();
              // 将海报数据写入本地文件
              fs.writeFileSync(tempFilePath, res.data, 'binary')
              wx.cloud.uploadFile({
                cloudPath: dishName, // 上传至云端的路径
                filePath: tempFilePath, // 小程序临时文件路径
                success: res => {
                  // 返回文件 ID
                  console.log(res.fileID)
                  wx.showToast({
                    title: '图片上传成功',
                  })
                },
                fail: error => {
                  console.error(error)
                  wx.showToast({
                    title: '图片上传失败',
                    icon: 'error'
                  })
                }
              })
            },
            fail(error) {
              wx.hideLoading()
              console.log(error)
            },
            complete() {
              that.setData({
                isSave: true
              })
            }
          })
        })
    }, 500)
  },
  print() {
    // 获取链接的蓝牙设备
    wx.getConnectedBluetoothDevices({
      success(res) {
        if (res.devices.length === 0) {
          wx.showToast({
            title: '请先连接打印机蓝牙设备',
            icon: 'error'
          })
        } else {
          const deviceId = res.devices[0].deviceId
          wx.getBLEDeviceServices({
            // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立连接
            deviceId,
            success(res) {
              console.log('device services:', res.services)
              // 打印
              this.createSelectorQuery()
                .select("#view")
                .node()
                .exec(res => {
                  const node = res[0].node
                  node.takeSnapshot({
                    type: 'arraybuffer',
                    format: 'png',
                    success: (res) => {
                      // 向蓝牙写数据
                      wx.writeBLECharacteristicValue({
                        deviceId,
                        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                        serviceId,
                        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                        characteristicId,
                        // 这里的value是ArrayBuffer类型
                        value: res.data,
                        success(res) {
                          console.log('writeBLECharacteristicValue success', res.errMsg)
                        }
                      })
                    },
                    fail(error) {
                      console.log(error)
                    }
                  })
                })
            },
            fail(error) {
              console.log(error)
            }
          })
        }
      },
      fail() {
        wx.showToast({
          title: '请先连接打印机蓝牙设备',
          icon: 'error'
        })
      }
    })
  },
  // 获取云函数获取图片的分辨率
  async getImageDPI(filePath) {
    wx.showLoading({
      title: '图片处理中请稍后...',
    })
    try {
      const now = new Date().getTime()
      const suffix = filePath.substring(filePath.lastIndexOf("."))
      const uploadRes = await wx.cloud.uploadFile({
        cloudPath: now + suffix, // 上传至云端的路径
        filePath: filePath, // 小程序临时文件路径
      })
      const dpi = await wx.cloud.callFunction({
        // 云函数名称
        name: 'getImageDpi',
        // 传给云函数的参数
        data: { cloudFileID: uploadRes.fileID }
      })
      return dpi.result
    } catch (error) {
      console.error(error)
    } finally {
      wx.hideLoading()
    }
  },
})
